package com.thinkgem.jeesite.common.utils;

import com.thinkgem.jeesite.common.config.Global;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * Created by aulbrother on 2017/8/22.
 */
public class I18nUtils{
    private static LocaleResolver localeResolver;

    private static LocaleResolver getLocaleResolver(){
        if(null == localeResolver){
            localeResolver = SpringContextHolder.getBean(LocaleResolver.class);
        }
        return localeResolver;
    }

    public static void setLocaleStr(String locale){
        CacheUtils.put("Locale", locale);
    }

    public static String getLocaleStr(){
        return (String)CacheUtils.get("Locale", (Object)Global.CN);
    }

    public static Locale setLocale(){
        LocaleResolver localLocaleResolver = getLocaleResolver();
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return localLocaleResolver.resolveLocale(request);
    }

    public static Locale getLocale(){
        LocaleResolver localLocaleResolver = getLocaleResolver();
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        return localLocaleResolver.resolveLocale(request);
    }

    /**
     * 获得i18n字符串
     */
    public static String getMessage(String code, Object[] args) {
        try{
            Locale localLocale = getLocale();
            return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
        }catch(Exception e){
            return code;
        }
    }
}
